<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        class="-mb-15px"
        label-width="68px"
    >
          <el-form-item label="审批结果" prop="status">
            <el-select
                v-model="queryParams.status"
                placeholder="请选择审批结果"
                clearable
                class="!w-240px"
            >
              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间" prop="createTime">
            <el-date-picker
                v-model="queryParams.createTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                class="!w-220px"
            />
          </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button plain type="primary" @click="handleCreate()">
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
            </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
            <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" :fit="true">

              <el-table-column label="序号" align="center" prop="id" />
              <el-table-column label="申请人" align="center" prop="userName" />
              <el-table-column
                    label="开始时间"
                    align="center"
                    prop="startTime"
                    width="180px"
                >
                <template #default="scope">
                  {{ formatStartDateTime(scope.row) }}
                </template>
              </el-table-column>

                <el-table-column
                    label="结束时间"
                    align="center"
                    prop="endTime"
                    width="180px"
                >
                <template #default="scope">
                  {{ formatEndDateTime(scope.row) }}
                </template>
              </el-table-column>
                <el-table-column label="出差时长" align="center" prop="duration">
                  <template #default="scope">
                    {{ scope.row.duration }} 小时
                  </template>
                </el-table-column>
                <el-table-column label="出差地点" align="center" prop="destination" />
                <el-table-column label="预算金额" align="center" prop="budgetAmount" />
                <el-table-column label="审批结果" align="center" prop="status">
                  <template #default="scope">
                    <dict-tag :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS" :value="scope.row.status" />
                  </template>
                </el-table-column>
                <el-table-column
                    label="申请时间"
                    align="center"
                    prop="createTime"
                    :formatter="dateFormatter"
                    width="180px"
                />
    <el-table-column label="操作" align="center" min-width="120px">
      <template #default="scope">
        <el-button
            v-hasPermi="['oa:business-trip-apply:query']"
            link
            type="primary"
            @click="handleDetail(scope.row)"
        >
          详情
        </el-button>
        <el-button
            v-hasPermi="['oa:business-trip-apply:query']"
            link
            type="primary"
            @click="handleProcessDetail(scope.row)"
        >
          进度
        </el-button>
        <el-button
            v-if="scope.row.result === 1"
            v-hasPermi="['oa:business-trip-apply:create']"
            link
            type="danger"
            @click="cancelProcess(scope.row)"
        >
          取消
        </el-button>
      </template>
    </el-table-column>
  </el-table>
    <!-- 分页 -->
    <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </ContentWrap>

  <DetailDrawer
    v-model="showDetailDrawer"
    :task-id="currentExpenseId"
    title="详情" />



  <ProcessInstanceDetailDrawer
    v-model="showDrawer" :process-instance-id="currentProcessInstanceId" title="流程进度"
    @success="handleDrawerSuccess" />
</template>
<script lang="ts" setup>
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import { dateFormatter,dateFormatter2,formatDate2 } from '@/utils/formatTime'
  import { BusinessTripApplyApi, BusinessTripApplyVO } from '@/api/oa/businesstripapply'
  import * as ProcessInstanceApi from '@/api/bpm/processInstance'
  import ProcessInstanceDetailDrawer from '@/views/bpm/processInstance/components/ProcessInstanceDetailDrawer.vue'
  import DetailDrawer from '@/views/oa/businesstripapply/components/DetailDrawer.vue'
  import { useUserStore } from '@/store/modules/user'

  defineOptions({ name: 'BusinessTripApply' })

  const message = useMessage() // 消息弹窗
  const router = useRouter() // 路由
  const { t } = useI18n() // 国际化
  const userStore = useUserStore()

  const loading = ref(true) // 列表的加载中
  const total = ref(0) // 列表的总页数
  const list = ref([]) // 列表的数据
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 10,
    userId: userStore.getUser.id,
    duration: undefined,
    status: undefined,
    processInstanceId: undefined,
    createTime: [],
  })
  const queryFormRef = ref() // 搜索的表单
  const showDetailDrawer = ref(false)
  const currentExpenseId = ref<number | undefined>(undefined)

  const showDrawer = ref(false)
  const currentProcessInstanceId = ref('')


  const handleDrawerSuccess = () => {
    showDrawer.value = false
    getList()
  }

  /** 查询列表 */
  const getList = async () => {
    loading.value = true
    try {
      const data = await BusinessTripApplyApi.getBusinessTripApplyPage(queryParams)
      list.value = data.list
      total.value = data.total
    } finally {
      loading.value = false
    }
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
  }

  /** 添加操作 */
  const handleCreate = () => {
    router.push({ name: 'BusinessTripApplyCreate' })
  }


  /** 详情操作 */
  const handleDetail = (row: BusinessTripApplyVO) => {
    currentExpenseId.value = row.id
    showDetailDrawer.value = true
  }

  /** 取消请假操作 */
  const cancelProcess = async (row) => {
    // 二次确认
    const { value } = await ElMessageBox.prompt('请输入取消原因', '取消流程', {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空，且非空格
      inputErrorMessage: '取消原因不能为空'
    })
    // 发起取消
    await ProcessInstanceApi.cancelProcessInstanceByStartUser(row.id, value)
    message.success('取消成功')
    // 刷新列表
    await getList()
  }

  /** 审批进度 */
  const handleProcessDetail = (row) => {
    currentProcessInstanceId.value = row.processInstanceId
    showDrawer.value = true
  }

  /** 格式化开始时间（日期+时间） */
  const formatStartDateTime = (row: BusinessTripApplyVO) => {
    if (!row.startTime) return '-'
    const dateStr = formatDate2(row.startTime)
    if (!row.startHour) return dateStr
    try {
      // startHour 可能是字符串、数组或对象，统一转换为字符串
      let hourStr = ''
      if (typeof row.startHour === 'string') {
        hourStr = row.startHour
      } else if (Array.isArray(row.startHour)) {
        // 如果是数组，取第一个元素（可能是 [hour, minute, second] 格式）
        hourStr = row.startHour.join(':')
      } else {
        hourStr = String(row.startHour)
      }
      // startHour 格式为 "HH:mm:ss"，我们只取 "HH:mm"
      return `${dateStr} ${hourStr.substring(0, 5)}`
    } catch (e) {
      console.error('formatStartDateTime error:', e, row.startHour)
      return dateStr
    }
  }

  /** 格式化结束时间（日期+时间） */
  const formatEndDateTime = (row: BusinessTripApplyVO) => {
    if (!row.endTime) return '-'
    const dateStr = formatDate2(row.endTime)
    if (!row.endHour) return dateStr
    try {
      // endHour 可能是字符串、数组或对象，统一转换为字符串
      let hourStr = ''
      if (typeof row.endHour === 'string') {
        hourStr = row.endHour
      } else if (Array.isArray(row.endHour)) {
        // 如果是数组，取第一个元素（可能是 [hour, minute, second] 格式）
        hourStr = row.endHour.join(':')
      } else {
        hourStr = String(row.endHour)
      }
      // endHour 格式为 "HH:mm:ss"，我们只取 "HH:mm"
      return `${dateStr} ${hourStr.substring(0, 5)}`
    } catch (e) {
      console.error('formatEndDateTime error:', e, row.endHour)
      return dateStr
    }
  }

  // fix: 列表不刷新的问题。
  watch(
      () => router.currentRoute.value,
      () => {
        getList()
      }
  )

  /** 初始化 **/
  onMounted(() => {
    getList()
  })
</script>
